import fragment from './glsl/ball.frag'
import vertex from './glsl/ball.vert'
import { defineProgram } from './webgl.js'

export const _ball = (gl) => {
    //初始化着色器
    var program = defineProgram(gl, vertex, fragment);
    let r = 8;
    let latitudeBands = 50;//纬度带
    let longitudeBands = 50;//经度带
    let positions_ = [];//存储x，y，z坐标
    let indices_ = [];//三角形列表（索引值）
    let textureCoordData = [];//存储纹理坐标u，v，纹理坐标与顶点坐标一一对应

    for (var latNum = 0; latNum <= latitudeBands; latNum++) {
        var lat = latNum * Math.PI / latitudeBands - Math.PI / 2;//纬度范围从-π/2到π/2
        var sinLat = Math.sin(lat);
        var cosLat = Math.cos(lat);

        for (var longNum = 0; longNum <= longitudeBands; longNum++) {
            var lon = longNum * 2 * Math.PI / longitudeBands - Math.PI;//经度范围从-π到π
            var sinLon = Math.sin(lon);
            var cosLon = Math.cos(lon);

            var x = cosLat * cosLon;
            var y = cosLat * sinLon;
            var z = sinLat;
            var u = (longNum / longitudeBands);
            var v = (latNum / latitudeBands);

            positions_.push(x);
            positions_.push(-z);
            positions_.push(y);
            textureCoordData.push(u);
            textureCoordData.push(v);
        }
    }


    for (var latNum = 0; latNum < latitudeBands; latNum++) {
        for (var longNum = 0; longNum < longitudeBands; longNum++) {
            var first = latNum * (longitudeBands + 1) + longNum;
            var second = first + longitudeBands + 1;

            indices_.push(first);
            indices_.push(second);
            indices_.push(first + 1);
            indices_.push(second);
            indices_.push(second + 1);
            indices_.push(first + 1);
        }
    }



    var position = new Float32Array(positions_);
    var indices = new Uint16Array(indices_);

    //创建缓冲区对象
    var vertexBuffer = gl.createBuffer();
    var indexBuffer = gl.createBuffer();
    if (!vertexBuffer || !indexBuffer) {
        console.log("无法创建缓冲区对象");
        return -1;
    }
    //绑定缓冲区对象并写入数据
    gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, position, gl.STATIC_DRAW);

    //获取数组中一个元素所占的字节数
    var fsize = position.BYTES_PER_ELEMENT;

    //获取attribute -> a_Position变量的存储地址
    var a_Position = gl.getAttribLocation(gl.program, "a_Position");
    if (a_Position < 0) {
        console.log("无法获取顶点位置的存储变量");
        return -1;
    }

    //对位置的顶点数据进行分配，并开启
    var numComponents = 3;
    var strideToNextPieceOfData = fsize * 3;
    var offsetIntoBuffer = 0;

    gl.vertexAttribPointer(a_Position, numComponents, gl.FLOAT, false, strideToNextPieceOfData, offsetIntoBuffer);
    gl.enableVertexAttribArray(a_Position);

    //将顶点索引数据写入缓冲区对象
    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
    gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);


    //设置视角矩阵的相关信息
    var u_ModelViewMatrix = gl.getUniformLocation(gl.program, "u_ModelViewMatrix");
    if (u_ModelViewMatrix < 0) {
        console.log("无法获取矩阵变量的存储位置");
        return;
    }

    //设置底色
    // gl.clearColor(0.0, 0.0, 0.0, 1.0);

    //进入场景初始化
    draw(gl, indices.length, u_ModelViewMatrix, positions_.length);
}



function draw(gl, indices_length, u_ModelViewMatrix, pos_len) {
    //设置视角矩阵的相关信息（视点，视线，上方向）
    var viewMatrix = new Matrix4();
    viewMatrix.setLookAt(12, 3, 7, -0.5, 0, 0, 0, 1, 0);

    //设置模型矩阵的相关信息
    var modelMatrix = new Matrix4();
    // modelMatrix.setRotate(0, 0, 5, 1);
    // modelMatrix.setTranslate(1, 0, 0);
    //console.log(modelMatrix);

    //设置透视投影矩阵
    var projMatrix = new Matrix4();
    projMatrix.setPerspective(20, canvas.width / canvas.height, 1, 3000);

    //计算出模型视图矩阵 viewMatrix.multiply(modelMatrix)相当于在着色器里面u_ViewMatrix * u_ModelMatrix
    var modeViewMatrix = projMatrix.multiply(viewMatrix.multiply(modelMatrix));

    //将试图矩阵传给u_ViewMatrix变量
    gl.uniformMatrix4fv(u_ModelViewMatrix, false, modeViewMatrix.elements);
    console.log("u_ModelViewMatrix", u_ModelViewMatrix)

    //开启隐藏面清除
    gl.enable(gl.DEPTH_TEST);

    //清空颜色和深度缓冲区
    // gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
    // 指定清空<canvas>的颜色
    gl.clearColor(0, 0, 0, 1.0);

    gl.clear(gl.COLOR_BUFFER_BIT);
    gl.viewport(0, 0, canvas.width, canvas.height);

    //绘制图形

    // gl.drawArrays(gl.LINE_STRIP,0, pos_len/3);
    console.log("indices length", indices_length)


    //这里有个坑，Uint16Array 需要对应 UNSIGNED_SHORT
    // Uint8Array 需要对应 UNSIGNED_BYTE
    gl.drawElements(gl.TRIANGLES, indices_length, gl.UNSIGNED_SHORT, 0);

}